package com.ligq.h265toupinpush.call

import android.util.Log
import com.ligq.common.utils.FileUtils
import org.java_websocket.WebSocket
import org.java_websocket.client.WebSocketClient
import org.java_websocket.handshake.ClientHandshake
import org.java_websocket.handshake.ServerHandshake
import org.java_websocket.server.WebSocketServer
import java.net.InetSocketAddress
import java.net.URI
import java.nio.ByteBuffer

const val SAVE_DATA = false
const val IS_XIAOMI = true

class SocketLive(
    private val player: ReceiveH264Player? = null,
    private val audioPlayer: AudioRecordLive? = null
) {
    constructor() : this(null, null)

    private lateinit var socket: WebSocket
    private lateinit var mClient: ReceiveClient
    private val mServer: WebSocketServer =
        object : WebSocketServer(InetSocketAddress(if (IS_XIAOMI) 9001 else 9002)) {
            override fun onOpen(conn: WebSocket?, handshake: ClientHandshake?) {
                socket = conn!!
            }

            override fun onClose(conn: WebSocket?, code: Int, reason: String?, remote: Boolean) {
                Log.d(TAG, "onClose: ")
            }

            override fun onMessage(conn: WebSocket?, message: String?) {
                Log.d(TAG, "onMessage: $message")
            }

            override fun onError(conn: WebSocket?, ex: Exception?) {
                Log.e(TAG, "onError: ", ex)
            }

            override fun onStart() {
                Log.d(TAG, "onStart: ")
            }
        }

    fun sendData(data: ByteArray) {
        sendData(-1, data)
    }

    fun sendData(type: Int, data: ByteArray) {
        if (this::socket.isInitialized && socket.isOpen) {
            var sendData = data
            //1表示视频数据包,2表示音频包
            if (type >= 0) {
                sendData = ByteArray(data.size + 1)
                sendData[0] = type.toByte()
                System.arraycopy(data, 0, sendData, 1, data.size)
            }
            socket.send(sendData)
        }
    }

    fun call() {
        mServer.start()
    }

    fun receive() {

        val uri: URI = if (IS_XIAOMI) {
            //华为手机
            URI("ws://192.168.1.2:9002")
        } else {
            //小米手机
            URI("ws://192.168.1.6:9001")
        }

        mClient = ReceiveClient(uri)
        try {
            mClient.connect()
        } catch (e: Exception) {
            Log.e(TAG, "start: ", e)
        }
    }

    inner class ReceiveClient(uri: URI) : WebSocketClient(uri) {
        override fun onOpen(handshakedata: ServerHandshake?) {
            Log.d(TAG, "onOpen: ")
        }

        override fun onMessage(message: String?) {
            Log.d(TAG, "onMessage: $message")
        }

        override fun onClose(code: Int, reason: String?, remote: Boolean) {
            Log.d(TAG, "onClose: ")
        }

        override fun onError(ex: java.lang.Exception?) {
            Log.e(TAG, "onError: ", ex)
        }

        override fun onMessage(bytes: ByteBuffer?) {
            bytes?.run {
                val receiveData = ByteArray(remaining())
                get(receiveData)
                Log.d(TAG, "onMessage: ${receiveData.contentToString()}")
                if (SAVE_DATA) {
                    FileUtils.writeBytes("receive.h264", receiveData)
                }
                //1表示视频,2表示音频
                when {
                    receiveData[0].toInt() == 2 -> {
                        audioPlayer?.playMusic(receiveData)
                    }
                    receiveData[0].toInt() == 1 -> {
                        player?.decode(receiveData)
                    }
                    else -> {
                        //do nothing
                    }
                }

            }

        }
    }

    fun close() {
        try {
            socket.close()
            mServer.stop()
        } catch (e: Exception) {
            Log.e(TAG, "close: ", e)
        }
    }
}